import MusenumUserModel from "../model/musenumUser";
import AppointTaskModel from "../model/appointTask";
import { gainAllSystemConfigLogin } from "../thirdServices/museumApi";
import MuseumHelper from "../middleware/museumHelper";
import { isMuseumPoolAvailable } from "../utils";
import log from "../utils/log";

class MuseumTask {
  appointList: string[] = [];
  async init() {
    let modelList: any[] = [];
    try {
      modelList = await AppointTaskModel.getAppointList(1);
    } catch (error) {
      console.log(error)
    }
    
    this.appointList = modelList.map(model => {
      const date = model.getDataValue('appointDate');
      const hallScheduleId = model.getDataValue('appointTime');
      if (hallScheduleId) {
        return `${date}-${hallScheduleId}`;
      } else {
        return `${date}`;
      }
    });
  };
  async execute() {
    if (this.appointList.length === 0) {
      return;
    }
    const model = await MusenumUserModel.findOneAvailable();
    if (model) {
      const token = model.getDataValue('token');
      const res = await gainAllSystemConfigLogin(token);
      if (res.data.code === 200) {
        // status 3 无票 0 闭馆  -1 暂未放票 4 有票 
        // ticketPool 剩余票数
        const list: any[] = res.data.data.calendarTicketPoolsByDate;//.filter(item => item.status === 4 && item.ticketPool > 0);
        const poolVOList: any[] = [];
        for (let i = 0; i< list.length; i++) {
          const ticket = list[i];
          if (isMuseumPoolAvailable(ticket)) {
            const hallTicketPoolVOS = ticket.hallTicketPoolVOS[0].scheduleTicketPoolVOS
            for (let j = 0; j < hallTicketPoolVOS.length; j++) {
              const poolVO = hallTicketPoolVOS[j];
              if (isMuseumPoolAvailable(poolVO)) {
                const ticketDate = `${ticket.currentDate}-${poolVO.hallScheduleId}`;
                // const ticketDate = `${ticket.currentDate}`;
                // 有需求
                if (this.appointList.includes(ticketDate)) {
                  poolVOList.push(poolVO);
                }
              }
            }
          }
        }
        if (poolVOList.length > 0) {
          log.debug('【博物馆】：有票');
          try {
            await this.createTick(poolVOList[0]); 
          } catch (error) {
            log.debug('错误:' + error.message);
          }
        }
      }
    }
  };

  async createTick(poolVO: any) {
    const model = await AppointTaskModel.findTask(poolVO.currentDate, 1);
    if (model) {
      const touristInfo = model.getDataValue('touristInfo') as string;
      const touristList = JSON.parse(touristInfo);
      const museumHelper = new MuseumHelper();
      const isBuy = await museumHelper.buy(poolVO, touristList);
      if (isBuy) {
        log.debug('【博物馆】：购票成功');
        // 更改任务状态
        const taskId = model.getDataValue('id');
        AppointTaskModel.update({ status: 0 }, taskId);
      } else {
        log.debug('【博物馆】：购票失败');
      }
    }
  }
}

export default MuseumTask;